﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Core;
using System.IO;
using SmartSapce.ServiceLocation;

namespace SmartSpace.WebApp._console.core
{
    public partial class application_add : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ICoreService service = ServiceLocator.Get<ICoreService>();
                _ctlListTheme.DataSource = service.GetThemes();
                _ctlListTheme.DataBind();
            }
            _ctlLinkBack.NavigateUrl = "./application-list.aspx";
        }

        protected void _ctlBtnSave_Click(object sender, EventArgs e)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();

            ImageFile image = new ImageFile();
            image.Id = Guid.NewGuid();
            image.Data = _ctlFileImage.FileBytes;
            image.Extension = new FileInfo(_ctlFileImage.FileName).Extension;

            if (service.SaveImage(image))
            {
                Application app = new Application();
                app.Id = Guid.NewGuid();
                app.Name = _ctlEditText.Text;
                app.ImageId = image.Id;
                app.ThemeId = new Guid(_ctlListTheme.SelectedValue);
                app.Type = service.GetTheme(app.ThemeId).Type;
                app.Copyright = _ctlEditCopyright.Text;
                service.SaveApplication(app);

                Response.Redirect(_ctlLinkBack.NavigateUrl);
            }
        }
    }
}